import base64
import os
import tkinter as tk
from tkinter import filedialog, messagebox, scrolledtext

class ICOToBase64Converter:
    def __init__(self, root):
        self.root = root
        self.root.title("ICO转Base64转换器")
        self.root.geometry("600x500")
        
        self.setup_ui()
    
    def setup_ui(self):
        # 选择文件区域
        file_frame = tk.Frame(self.root)
        file_frame.pack(pady=10, padx=20, fill=tk.X)
        
        tk.Button(file_frame, text="选择ICO文件", command=self.select_file).pack(side=tk.LEFT)
        self.file_label = tk.Label(file_frame, text="未选择文件", wraplength=400)
        self.file_label.pack(side=tk.LEFT, padx=10)
        
        # 转换按钮
        tk.Button(self.root, text="转换为Base64", command=self.convert, 
                 bg="lightblue", font=("Arial", 12)).pack(pady=10)
        
        # 结果显示区域
        result_frame = tk.Frame(self.root)
        result_frame.pack(pady=10, padx=20, fill=tk.BOTH, expand=True)
        
        tk.Label(result_frame, text="Base64编码结果:").pack(anchor=tk.W)
        self.result_text = scrolledtext.ScrolledText(result_frame, height=15, width=70)
        self.result_text.pack(fill=tk.BOTH, expand=True)
        
        # 操作按钮区域
        button_frame = tk.Frame(self.root)
        button_frame.pack(pady=10)
        
        tk.Button(button_frame, text="复制到剪贴板", command=self.copy_to_clipboard).pack(side=tk.LEFT, padx=5)
        tk.Button(button_frame, text="保存到文件", command=self.save_to_file).pack(side=tk.LEFT, padx=5)
        tk.Button(button_frame, text="生成HTML", command=self.generate_html).pack(side=tk.LEFT, padx=5)
    
    def select_file(self):
        file_path = filedialog.askopenfilename(
            title="选择ICO文件",
            filetypes=[("ICO files", "*.ico"), ("All files", "*.*")]
        )
        if file_path:
            self.file_path = file_path
            self.file_label.config(text=file_path)
    
    def convert(self):
        if not hasattr(self, 'file_path'):
            messagebox.showerror("错误", "请先选择ICO文件")
            return
        
        try:
            with open(self.file_path, 'rb') as file:
                ico_data = file.read()
                base64_encoded = base64.b64encode(ico_data).decode('utf-8')
            
            self.base64_result = base64_encoded
            self.result_text.delete(1.0, tk.END)
            self.result_text.insert(tk.END, base64_encoded)
            
            messagebox.showinfo("成功", f"转换完成!\nBase64长度: {len(base64_encoded)} 字符")
            
        except Exception as e:
            messagebox.showerror("错误", f"转换失败: {e}")
    
    def copy_to_clipboard(self):
        if hasattr(self, 'base64_result'):
            self.root.clipboard_clear()
            self.root.clipboard_append(self.base64_result)
            messagebox.showinfo("成功", "Base64编码已复制到剪贴板")
        else:
            messagebox.showerror("错误", "没有可复制的数据")
    
    def save_to_file(self):
        if hasattr(self, 'base64_result'):
            file_path = filedialog.asksaveasfilename(
                title="保存Base64编码",
                defaultextension=".txt",
                filetypes=[("Text files", "*.txt"), ("All files", "*.*")]
            )
            if file_path:
                try:
                    with open(file_path, 'w', encoding='utf-8') as file:
                        file.write(self.base64_result)
                    messagebox.showinfo("成功", f"Base64编码已保存到: {file_path}")
                except Exception as e:
                    messagebox.showerror("错误", f"保存失败: {e}")
    
    def generate_html(self):
        if hasattr(self, 'base64_result'):
            file_path = filedialog.asksaveasfilename(
                title="保存HTML文件",
                defaultextension=".html",
                filetypes=[("HTML files", "*.html"), ("All files", "*.*")]
            )
            if file_path:
                try:
                    html_code = f'''<!DOCTYPE html>
<html>
<head>
    <title>ICO Base64示例</title>
    <link rel="icon" href="data:image/x-icon;base64,{self.base64_result}" type="image/x-icon">
    <style>
        body {{ font-family: Arial, sans-serif; margin: 40px; }}
        .info {{ background: #f0f0f0; padding: 15px; border-radius: 5px; }}
    </style>
</head>
<body>
    <h1>ICO Base64示例页面</h1>
    <div class="info">
        <p>此页面的favicon使用Base64编码的ICO文件。</p>
        <p>Base64长度: {len(self.base64_result)} 字符</p>
    </div>
</body>
</html>'''
                    
                    with open(file_path, 'w', encoding='utf-8') as file:
                        file.write(html_code)
                    messagebox.showinfo("成功", f"HTML文件已保存到: {file_path}")
                except Exception as e:
                    messagebox.showerror("错误", f"生成HTML失败: {e}")

# 使用方法
if __name__ == "__main__":
    # 如果要使用命令行版本，取消下面的注释
    # main()
    
    # 使用GUI版本
    root = tk.Tk()
    app = ICOToBase64Converter(root)
    root.mainloop()